<template>
  <div>
    <div v-for="(row, i) in valueModel" :key="element.key + '_' + i" style="display: flex; align-items: center">
      <a-row
        :key="row.key"
        style="flex: 1"
        type="flex"
        class="fixed-row"
        :gutter="element.options.gutter ?? 0"
        :justify="element.options.justify"
        :align="element.options.align"
      >
        <template v-if="element.fieldCode === fixedCombinationFieldCode.piInfo">
          <a-col :span="element.options.columns[0].gridLayoutNumber">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.piInfo.piMajor + '_' + i"
              :rules="{
                required: true,
                validator: checkPiMajor,
                trigger: 'change'
              }"
            >
              <template #label>
                {{ element.options.columns[0].name }}
                <a-tooltip>
                  <template #title>找不到专业？请联系机构老师</template>
                  <i
                    class="wentishuoming icpIconfont hover-primary cursor-pointer"
                    style="font-size: 20px; line-height: normal"
                  ></i>
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.profession.label || '--' }}
                <span
                  v-if="approvalPermission"
                  class="ml-4 cursor-pointer project-num"
                  @click="
                    gotoClick(
                      'majorIdList',
                      row.profession.value,
                      `【${row.profession.label}】在研项目${majorObj[row.profession.value] || 0}个`
                    )
                  "
                  >在研项目{{ majorObj[row.profession.value] || 0 }}个</span
                >
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.profession.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'majorName', value: 'majorId' }"
                  :options="professionArrRow[row.key]"
                  :get-popup-container="getPopupContainer"
                  @search="
                    (val) => {
                      handleSearchProfession(row.key, val, i)
                    }
                  "
                  @change="
                    (val) => {
                      changeProfession(row.key, val, i)
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[1].gridLayoutNumber">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.piInfo.piName + '_' + i"
              :rules="{
                required: true,
                validator: checkPiName,
                trigger: 'change'
              }"
            >
              <template #label> {{ element.options.columns[1].name }} </template>
              <template v-if="disabled">
                {{ row.pi.fullLabel || '--' }}
                <span
                  v-if="approvalPermission"
                  class="ml-4 cursor-pointer project-num"
                  @click="
                    gotoClick('queryInfo', row.pi.value, `【${row.pi.label}】在研项目${piObj[row.pi.value] || 0}个`)
                  "
                  >在研项目{{ piObj[row.pi.value] || 0 }}个</span
                >
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.pi.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :get-popup-container="getPopupContainer"
                  @search="
                    (val) => {
                      handleSearchPi(row.key, val, i)
                    }
                  "
                  @change="
                    (val) => {
                      changePi(row.key, val, i)
                    }
                  "
                >
                  <a-select-option
                    v-for="piOpt of piArrRow[row.key]"
                    :key="piOpt.userId"
                    :value="piOpt.userId"
                    :label="piOpt.name"
                  >
                    {{ piOpt.name + '（' + piOpt.mobile + ')' }}
                  </a-select-option>
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[2].gridLayoutNumber">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.piInfo.piTitle + '_' + i"
              :rules="{
                required: true,
                validator: checkPiTitle,
                trigger: 'blur'
              }"
            >
              <template #label> {{ element.options.columns[2].name }} </template>
              <template v-if="disabled">
                {{ row.titleType || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.titleType"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <template v-else-if="element.fieldCode === fixedCombinationFieldCode.sponsorInfo">
          <a-col :span="element.options.columns[0].gridLayoutNumber">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.sponsorInfo.sponsorOrg + '_' + i"
              :rules="{
                required: true,
                validator: checkSponsorOrg,
                trigger: 'change'
              }"
            >
              <template #label>
                {{ element.options.columns[0].name }}
                <a-tooltip>
                  <template #title>找不到申办方？请联系客服更新；项目无申办方，请选择N/A</template>
                  <i
                    class="wentishuoming icpIconfont hover-primary cursor-pointer"
                    style="font-size: 20px; line-height: normal"
                  ></i>
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.orgInfo.label || '--' }}
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.orgInfo.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="
                    disabledFieldCodes.includes(fixedCombinationFieldCode.sponsorInfo) ||
                    element.options.readonlyFlag === 1
                  "
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'orgName', value: 'orgId' }"
                  :options="orgArrRow[row.key]"
                  :get-popup-container="getPopupContainer"
                  @search="
                    (val) => {
                      handleSearchOrg(row.key, val, i)
                    }
                  "
                  @change="
                    (val) => {
                      changeOrg(row.key, val, i)
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[1].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.sponsorInfo.sponsorContact + '_' + i">
              <template #label> {{ element.options.columns[1].name }} </template>
              <template v-if="disabled">
                {{ row.contactName || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.contactName"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[2].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.sponsorInfo.sponsorPhone + '_' + i">
              <template #label> {{ element.options.columns[2].name }} </template>
              <template v-if="disabled">
                {{ row.contactPhone || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.contactPhone"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <template v-else-if="element.fieldCode === fixedCombinationFieldCode.croInfo">
          <a-col :span="element.options.columns[0].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.croInfo.croOrg + '_' + i">
              <template #label>
                {{ element.options.columns[0].name }}
                <a-tooltip>
                  <template #title>找不到CRO？请联系客服更新</template>
                  <i
                    class="wentishuoming icpIconfont hover-primary cursor-pointer"
                    style="font-size: 20px; line-height: normal"
                  ></i>
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.orgInfo.label || '--' }}
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.orgInfo.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'orgName', value: 'orgId' }"
                  :options="orgArrRow[row.key]"
                  :get-popup-container="getPopupContainer"
                  @search="
                    (val) => {
                      handleSearchOrg(row.key, val, i)
                    }
                  "
                  @change="
                    (val) => {
                      changeOrg(row.key, val, i)
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[1].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.croInfo.croContact + '_' + i">
              <template #label> {{ element.options.columns[1].name }} </template>
              <template v-if="disabled">
                {{ row.contactName || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.contactName"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[2].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.croInfo.croPhone + '_' + i">
              <template #label> {{ element.options.columns[2].name }} </template>
              <template v-if="disabled">
                {{ row.contactPhone || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.contactPhone"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <template v-else-if="element.fieldCode === fixedCombinationFieldCode.smoInfo">
          <a-col :span="element.options.columns[0].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.smoInfo.smoOrg + '_' + i">
              <template #label>
                {{ element.options.columns[0].name }}
                <a-tooltip>
                  <template #title>找不到SMO？请联系客服更新</template>
                  <i
                    class="wentishuoming icpIconfont hover-primary cursor-pointer"
                    style="font-size: 20px; line-height: normal"
                  ></i>
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.orgInfo.label || '--' }}
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.orgInfo.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'orgName', value: 'orgId' }"
                  :options="orgArrRow[row.key]"
                  :get-popup-container="getPopupContainer"
                  @search="
                    (val) => {
                      handleSearchOrg(row.key, val, i)
                    }
                  "
                  @change="
                    (val) => {
                      changeOrg(row.key, val, i)
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[1].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.smoInfo.smoContact + '_' + i">
              <template #label> {{ element.options.columns[1].name }} </template>
              <template v-if="disabled">
                {{ row.contactName || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.contactName"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[2].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.smoInfo.smoPhone + '_' + i">
              <template #label> {{ element.options.columns[2].name }} </template>
              <template v-if="disabled">
                {{ row.contactPhone || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.contactPhone"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <template v-else-if="element.fieldCode === fixedCombinationFieldCode.thirdCheckInfo">
          <a-col :span="element.options.columns[0].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.thirdCheckInfo.thirdCheckOrg + '_' + i">
              <template #label>
                {{ element.options.columns[0].name }}
                <a-tooltip>
                  <template #title>找不到第三方检测单位？请联系客服更新</template>
                  <i
                    class="wentishuoming icpIconfont hover-primary cursor-pointer"
                    style="font-size: 20px; line-height: normal"
                  ></i>
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.orgInfo.label || '--' }}
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.orgInfo.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'orgName', value: 'orgId' }"
                  :options="orgArrRow[row.key]"
                  :get-popup-container="getPopupContainer"
                  @search="
                    (val) => {
                      handleSearchOrg(row.key, val, i)
                    }
                  "
                  @change="
                    (val) => {
                      changeOrg(row.key, val, i)
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[1].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.thirdCheckInfo.thirdCheckContact + '_' + i">
              <template #label> {{ element.options.columns[1].name }} </template>
              <template v-if="disabled">
                {{ row.contactName || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.contactName"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[2].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.thirdCheckInfo.thirdCheckPhone + '_' + i">
              <template #label> {{ element.options.columns[2].name }} </template>
              <template v-if="disabled">
                {{ row.contactPhone || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value.trim="row.contactPhone"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <template v-else-if="element.fieldCode === fixedCombinationFieldCode.thirdCheckInfo">
          <a-col :span="element.options.columns[0].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.thirdCheckInfo.thirdCheckOrg + '_' + i">
              <template #label>
                {{ element.options.columns[0].name }}
                <a-tooltip>
                  <template #title>找不到第三方检测单位？请联系客服更新</template>
                  <i
                    class="wentishuoming icpIconfont hover-primary cursor-pointer"
                    style="font-size: 20px; line-height: normal"
                  ></i>
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.orgInfo.label || '--' }}
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.orgInfo.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'orgName', value: 'orgId' }"
                  :options="orgArrRow[row.key]"
                  :get-popup-container="getPopupContainer"
                  @search="
                    (val) => {
                      handleSearchOrg(row.key, val, i)
                    }
                  "
                  @change="
                    (val) => {
                      changeOrg(row.key, val, i)
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[1].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.thirdCheckInfo.thirdCheckContact + '_' + i">
              <template #label> {{ element.options.columns[1].name }} </template>
              <template v-if="disabled">
                {{ row.contactName || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.contactName"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="element.options.columns[2].gridLayoutNumber">
            <a-form-item :colon="false" :name="fixedCombinationCode.thirdCheckInfo.thirdCheckPhone + '_' + i">
              <template #label> {{ element.options.columns[2].name }} </template>
              <template v-if="disabled">
                {{ row.contactPhone || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.contactPhone"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <div v-if="!disabled" class="btn-group">
          <template
            v-if="
              element.fieldCode !== fixedCombinationFieldCode.sponsorInfo ||
              (element.fieldCode === fixedCombinationFieldCode.sponsorInfo &&
                !disabledFieldCodes.includes(fixedCombinationFieldCode.sponsorInfo))
            "
          >
            <i
              v-if="element.options.maxCycleNumber > valueModel.length"
              style="color: #0177fd; font-size: 24px"
              class="tianjia1 icpIconfont"
              @click="addRow(i)"
            ></i>
            <i
              v-if="valueModel.length > 1"
              style="color: #fe5a5a; font-size: 24px"
              class="jianqu icpIconfont"
              @click="reduceRow(row.key, i)"
            ></i>
          </template>
        </div>
      </a-row>
    </div>
  </div>

  <!--查看在研项目-->
  <a-modal
    v-model:visible="visible"
    :mask-closable="false"
    :keyboard="false"
    width="100%"
    :body-style="{ height: height + 'px' }"
    :title="title"
    :centered="true"
    :footer="null"
  >
    <!-- TnDataTable -->
    <TnNewTable v-if="visible" ref="tableRef" :columns="columns" :tn-table-props="tnTableProps" :query-data="queryData">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'projectName'">
          <OrgStar v-if="record.projectPriority" />
          {{ record.projectName }}
        </template>
        <template v-if="column.dataIndex === 'projectOrgListShow'">
          {{ getProjectOrgListValue(record.projectOrgList || [], 'orgName') }}
        </template>
        <template v-if="column.dataIndex === 'majorNameShow'">
          {{ getProjectProfessionListValue(record.projectProfessionList || [], 'majorName') }}
        </template>
        <template v-if="column.dataIndex === 'piNameShow'">
          {{ getProjectProfessionListValue(record.projectProfessionList || [], 'piName') }}
        </template>
        <template v-if="column.dataIndex === 'projectStatusShow'">
          <a-tag v-if="record.projectStatus" :color="getTagType(record.projectStatus)">{{
            PROJECT_STATUS_MAP[record.projectStatus].label
          }}</a-tag>
        </template>
      </template>
    </TnNewTable>
  </a-modal>
</template>

<script lang="ts" setup>
import { PropType, ref, computed, nextTick } from 'vue'
import { WidgetForm } from './config/antd'
import {
  queryProfessionByOrg,
  queryPiByProfession,
  queryOrgByOrgType,
  queryMajorInResearchNum,
  queryPiInResearchNum,
  queryInResearchProjectInfo
} from '@@/api/form'
// import { RemoveCircle, AddCircle } from '@vicons/ionicons5'
import { fixedCombinationFieldCode, fixedCombinationCode } from './config/enum'
import { v4 } from 'uuid'
import { debounce } from 'lodash-es'
// import { useRouter } from 'vue-router'
// import { getUserGrantProjectlist } from '@/api/project'
import { PROJECT_STATUS_MAP } from '@@/enums/projectEnums'

// const router = useRouter()

const props = defineProps({
  config: {
    type: Object as PropType<WidgetForm['config']>,
    default: () => ({}),
    required: true
  },
  element: {
    type: Object,
    default: () => ({}),
    required: true
  },
  remoteReplace: {
    type: Object,
    default: () => ({}),
    required: true
  },
  model: {
    type: Object,
    default: () => ({}),
    required: true
  },
  disabled: {
    type: Boolean,
    default: true,
    required: true
  },
  disabledFieldCodes: {
    type: Array,
    default: () => [],
    required: true
  },
  approvalPermission: {
    type: Boolean,
    default: false
  }
})

const getPopupContainer: any = (targetElement) => {
  return targetElement.closest('.ant-form')
}

const valueModel = computed({
  get: () => props.model[props.element.model],
  set: (val) => {
    // eslint-disable-next-line vue/no-mutating-props
    props.model[props.element.model] = val
  }
})

const piArrRow = ref<any>({})

const initPiArr = (key, majorId, searchVal?, index?) => {
  if (props.disabled) {
    // 表单禁用，直接返回
    return
  }
  if (!majorId) {
    // 未选择专业
    piArrRow.value[key] = []
    return
  }
  if (searchVal === undefined || searchVal === null || searchVal === '') {
    if (index !== undefined && index !== null) {
      // 未输入搜索条件时，以选中值的label作为搜索
      searchVal = valueModel.value[index].pi.label
    }
  }
  const queryObj = { pageSize: 20, pageNum: 1, orgId: props.remoteReplace.orgId, majorId, searchVal: searchVal ?? '' }
  queryPiByProfession(queryObj).then((res) => {
    piArrRow.value[key] = res.list
  })
}

// 所有专业选项（不同行的专业以key区分）
const professionArrRow = ref<any>({})

/**
 * 初始化专业选项
 * @param key 每行主键
 * @param searchVal 搜索条件（专业名称）
 * @param searchVal 行下标
 */
const initProfessionArr = (key, searchVal?, index?) => {
  if (props.disabled) {
    // 表单禁用，直接返回
    return
  }
  if (searchVal === undefined || searchVal === null || searchVal === '') {
    if (index !== undefined && index !== null) {
      // 未输入搜索条件时，以选中值的label作为搜索
      searchVal = valueModel.value[index].profession.label
    }
  }
  const queryObj = { pageSize: 20, pageNum: 1, orgId: props.remoteReplace.orgId, searchVal: searchVal ?? '' }
  queryProfessionByOrg(queryObj).then((res) => {
    professionArrRow.value[key] = res.list
  })
}

const orgArrRow = ref<any>({})

const initOrgArr = (key, searchVal?, index?) => {
  if (props.disabled) {
    // 表单禁用，直接返回
    return
  }
  const orgType = getOrgType()
  if (orgType === null) {
    // 组织类型为空，直接返回
    return
  }
  if (searchVal === undefined || searchVal === null || searchVal === '') {
    if (index !== undefined && index !== null) {
      // 未输入搜索条件时，以选中值的label作为搜索
      searchVal = valueModel.value[index].orgInfo.label
    }
  }
  const queryObj = { pageSize: 20, pageNum: 1, orgType, searchVal: searchVal ?? '' }
  queryOrgByOrgType(queryObj).then((res) => {
    orgArrRow.value[key] = res.list
  })
}

/**
 * 增加行
 * @param index 下标
 */
const addRow = (index) => {
  const rowObj: any = {}
  rowObj.key = v4().replaceAll('-', '')
  if (props.element.fieldCode === fixedCombinationFieldCode.piInfo) {
    rowObj.profession = {}
    rowObj.pi = {}
    initProfessionArr(rowObj.key)
  } else {
    const arr = [
      fixedCombinationFieldCode.sponsorInfo,
      fixedCombinationFieldCode.croInfo,
      fixedCombinationFieldCode.smoInfo,
      fixedCombinationFieldCode.thirdCheckInfo
    ]
    if (arr.includes(props.element.fieldCode)) {
      rowObj.orgInfo = {}
      initOrgArr(rowObj.key)
    }
  }
  valueModel.value.splice(index + 1, 0, rowObj)
  if (props.element.fieldCode === fixedCombinationFieldCode.piInfo) {
    piArrRow.value[rowObj.key] = []
  }
}

/**
 * 移除行
 * @param key 行key
 * @param index 行下标
 */
const reduceRow = (key, index) => {
  valueModel.value.splice(index, 1)
  if (props.element.fieldCode === fixedCombinationFieldCode.piInfo) {
    delete piArrRow.value[key]
  }
}

/**
 * 初始化行
 */
const initRow = () => {
  if (valueModel.value.length === 0) {
    addRow(0)
  } else {
    valueModel.value.forEach((row) => {
      row.key = v4().replaceAll('-', '')
      if (props.element.fieldCode === fixedCombinationFieldCode.piInfo) {
        piArrRow.value[row.key] = []
        initProfessionArr(row.key, row.profession?.label)
        if (row && row.profession && row.profession.value) {
          // 初始化主要研究者选项
          initPiArr(row.key, row.profession.value)
        }
      } else {
        initOrgArr(row.key, row.orgInfo?.label)
      }
    })
  }
}

/**
 * 远程搜索专业
 */
const handleSearchProfession = debounce((key, val, i) => {
  initProfessionArr(key, val, i)
}, 500)

/**
 * 远程搜索专业下的PI
 */
const handleSearchPi = debounce((key, val, i) => {
  initPiArr(key, valueModel.value[i].profession?.value, val, i)
}, 500)

/**
 * 远程搜索组织
 */
const handleSearchOrg = debounce((key, val, i) => {
  initOrgArr(key, val, i)
}, 500)

/**
 * 根据固定组合字段编码获取组织类型
 */
const getOrgType = () => {
  if (props.element.fieldCode === fixedCombinationFieldCode.sponsorInfo) {
    return 3
  } else if (props.element.fieldCode === fixedCombinationFieldCode.croInfo) {
    return 4
  } else if (props.element.fieldCode === fixedCombinationFieldCode.smoInfo) {
    return 5
  } else if (props.element.fieldCode === fixedCombinationFieldCode.thirdCheckInfo) {
    return 8
  }
  return null
}

/**
 * 专业change事件
 * @param key 行主键
 * @param val 变化后的值
 * @param index 行索引
 */
const changeProfession = (key, val, index) => {
  // 设置专业的名称
  const option = professionArrRow.value[key].find((opt) => opt.majorId === val)
  if (option) {
    valueModel.value[index].profession.label = option.majorName
  } else {
    // 清空选项时，选项重置
    valueModel.value[index].profession.label = null
    initProfessionArr(key)
  }
  valueModel.value[index].pi = {}
  valueModel.value[index].titleType = null
  const majorId = valueModel.value[index].profession.value
  if (!majorId) {
    piArrRow.value[key] = []
    return
  }
  // 初始化主要研究者选项
  initPiArr(key, majorId)
}

const changePi = (key, val, index) => {
  const piOpt = piArrRow.value[key].find((temp) => temp.userId === val)
  if (piOpt) {
    valueModel.value[index].pi.label = piOpt.name
    valueModel.value[index].pi.fullLabel = piOpt.name + '（' + piOpt.mobile + '）'
    if (piOpt.titleType) {
      valueModel.value[index].titleType = piOpt.titleType
    } else {
      valueModel.value[index].titleType = null
    }
  } else {
    valueModel.value[index].titleType = null
    // 清空选项时，选项重置
    valueModel.value[index].pi.label = null
    initPiArr(key, valueModel.value[index].profession?.value)
  }
}

/**
 * 校验PI专业
 */
const checkPiMajor = async (_rule: any) => {
  const name = _rule.field
  const piObj = valueModel.value[Number(name.replace(fixedCombinationCode.piInfo.piMajor + '_', ''))]
  const value = piObj.profession.value
  if (_rule.required) {
    if (value) {
      return Promise.resolve()
    }
    // 必填
    return Promise.reject('请选择本中心承担的专业')
  }
  return Promise.resolve()
}

/**
 * 校验PI名称
 */
const checkPiName = async (_rule: any) => {
  const name = _rule.field
  const piObj = valueModel.value[Number(name.replace(fixedCombinationCode.piInfo.piName + '_', ''))]
  const value = piObj.pi.value
  if (_rule.required) {
    if (value) {
      return Promise.resolve()
    }
    // 必填
    return Promise.reject('请选择本中心主要研究者')
  }
  return Promise.resolve()
}

/**
 * 校验PI职称
 */
const checkPiTitle = async (_rule: any) => {
  const name = _rule.field
  const piObj = valueModel.value[Number(name.replace(fixedCombinationCode.piInfo.piTitle + '_', ''))]
  const value = piObj.titleType
  if (_rule.required) {
    if (value) {
      return Promise.resolve()
    }
    // 必填
    return Promise.reject('请选择本中心主要研究者职称')
  }
  return Promise.resolve()
}

/**
 * 改变组织
 */
const changeOrg = (key, val, index) => {
  // 设置组织的名称
  const option = orgArrRow.value[key].find((opt) => opt.orgId === val)
  if (option) {
    valueModel.value[index].orgInfo.label = option.orgName
  } else {
    // 清空选项时，选项重置
    valueModel.value[index].orgInfo.label = null
    initOrgArr(key)
  }
}

/**
 * 校验申办方
 */
const checkSponsorOrg = async (_rule: any) => {
  const name = _rule.field
  const sponsorInfo = valueModel.value[Number(name.replace(fixedCombinationCode.sponsorInfo.sponsorOrg + '_', ''))]
  const value = sponsorInfo.orgInfo.value
  if (_rule.required) {
    if (value) {
      return Promise.resolve()
    }
    // 必填
    return Promise.reject('请选择申办方')
  }
  return Promise.resolve()
}

/**
 * 获取pi在研项目数
 */
const piObj = ref<any>({})
const queryProjectNumByPI = async (piIds) => {
  try {
    const params = {
      piIds
    }
    const res = await queryPiInResearchNum(params)
    piObj.value[piIds] = res
  } catch {
    console.log('pi catch')
    piObj.value[piIds] = '111'
  }
}

/**
 * 获取专业在研项目数
 */
const majorObj = ref<any>({})
const queryProjectNumByMajor = async (majorIds) => {
  try {
    const params = {
      majorIds
    }
    const res = await queryMajorInResearchNum(params)
    console.log(res)
    majorObj.value[majorIds] = res
  } catch {
    console.log('major catch')
    majorObj.value[majorIds] = '222'
  }
}

const init = () => {
  if (props.disabled) {
    ;(valueModel.value || []).forEach((item) => {
      if (item.pi?.value) {
        queryProjectNumByPI(item.pi.value)
      }
      if (item.profession?.value) {
        queryProjectNumByMajor(item.profession.value)
      }
    })
  }
}

init()

const visible = ref(false)
const title = ref('')
const columns: any = [
  {
    title: '项目名称',
    dataIndex: 'projectName',
    minWidth: 400,
    fixed: 'left',
    ellipsis: { showTitle: true }
  },
  {
    title: '项目编号',
    dataIndex: 'projectNo',
    minWidth: 120
  },
  {
    title: '试验方案编号',
    dataIndex: 'projectPlanNo',
    minWidth: 130
  },
  {
    title: '试验类型',
    dataIndex: 'projectType',
    minWidth: 100
  },
  {
    title: '试验分期',
    dataIndex: 'stages',
    minWidth: 100
  },
  {
    title: '申办方',
    dataIndex: 'projectOrgListShow',
    minWidth: 170
  },
  {
    title: '承担专业',
    dataIndex: 'majorNameShow',
    minWidth: 130
  },
  {
    title: '主要研究者',
    dataIndex: 'piNameShow',
    minWidth: 130
  },
  {
    title: '项目状态',
    dataIndex: 'projectStatusShow',
    minWidth: 100
  }
]
const tnTableProps = {
  name: 'GenerateFixedCombinationResearchProjects',
  asyncApi: queryInResearchProjectInfo,
  // otherTabelHeight: 280,
  // maxHeight: window.innerHeight - 150,
  initRequest: false
}
const height = window.innerHeight - 150
const queryData = ref<any>({})

const tableRef = ref()
const reload = (page = 1) => {
  tableRef.value.reloadTable(page)
}
const gotoClick = async (feild, value, titleStr) => {
  visible.value = true
  title.value = titleStr
  queryData.value.queryType = feild === 'majorIdList' ? 1 : 0
  queryData.value.ids = value
  await nextTick()
  reload()
  // router.push({ path: '/projectCenter/index', query: { [feild]: value } })
}
const getProjectOrgListValue = (arr, value) => {
  const textArr: any[] = []
  arr.forEach((item: any) => {
    if (item.orgType === 3) {
      textArr.push(item[value])
    }
  })
  return textArr.join(',')
}

const getProjectProfessionListValue = (arr, value) => {
  const textArr: any = []
  arr.forEach((item) => {
    if (item.majorId) {
      textArr.push(item[value])
    }
  })
  return textArr.join(',')
}

const getTagType = (status) => {
  const statusList = {
    13: 'processing',
    21: 'processing',
    22: 'error',
    31: 'error',
    32: 'success',
    41: 'error',
    99: 'error'
  }
  return statusList[status] || ''
}

initRow()

defineExpose({})
</script>

<style lang="less" scoped>
:deep(.btn-group) {
  margin-top: 24px;
  span {
    cursor: pointer;
  }
}
.fixed-row {
  flex-flow: nowrap !important;
}
.project-num {
  color: @primary-color;
  font-style: italic;
  text-decoration: underline;
}
</style>
